var WxFileRead = {
   readLocalFile:function(localPath,cb){
     wx.getFileSystemManager().readFile({
       filePath: wx.env.USER_DATA_PATH+'/'+localPath,
       encoding: 'utf8',
       success: function (content) {
         cb(null, JSON.parse(content.data))
       },
       fail: function (e) {
        cb(e);
       }
     })
   },
   downRemoteUrlFile:function(remoteUrl,localPath,cb){
     wx.downloadFile({
       url: remoteUrl,
       filePath: wx.env.USER_DATA_PATH+'/'+localPath,
       success: function (r) {
         cc.log('下载成功:',remoteUrl, r)
         cb(null,r);
       },
       failt: function (e) {
         cc.log('下载失败')
         cb(e)
       }
     })
   },
   getJsonFile:function(local,remote,version,cb){
     WxFileRead.readLocalFile(local,function(err,content){
        if(err || content.data.gameConfig.version != version){
          console.log('config匹配失败，准备去下载:',content.data.gameConfig.version,version);
          WxFileRead.downRemoteUrlFile(remote,local,function(e,remote){
              if(e){
                cb(e,null)
              } else {
                WxFileRead.readLocalFile(local,cb);
              }
          })
        } else {
          console.log('config匹配成功',content.data.gameConfig.version);
          cb(null,content);
        }
     })
   },

   getConfigFile:function(local,remote,version,cb){
      // if(CC_WECHATGAME){
      //    this.getJsonFile(local,remote,version,cb)
      // } else {
        if(cc.sys.isNative){
          var xhr = cc.loader.getXMLHttpRequest();
          xhr.open("GET", remote, true);
          xhr.onreadystatechange = function () {
              if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
                  cc.log('resp:' + xhr.response);
                  var data = null;
                  try {
                      data = JSON.parse(xhr.response);
                  } catch (e) {
                      cb(e, null);
                      cc.error("err:" + e);
                      return;
                  }
                  if (!!cb && data.code === 200) {
                      cb(null, data);
                  } else {
                      cb(data.code, data.data);

                      cc.log('登陆失败！' + data);
                      UI.ToolTip({ message: data.msg });
                  }
              } else {
                  // cc.log("xhr.readyState,xhr.status", xhr.readyState, xhr.status);
              }
          };
          xhr.send();
        } else {
          cc.loader.load(remote,function(err,res){
            try{
              var a = JSON.parse(res);
              cb(err,a)
            }catch(e){
              cb(e,null)
            }
          });
        }
        
      // }
   }
}

module.exports = WxFileRead;
